package com.secsbrain.development.web.ws.handle;

import com.alibaba.fastjson.JSON;
import com.secsbrain.development.web.ws.base.BaseHandler;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;

/**
 * 消息通知socket
 * Created by yangyang.zhang on 2017-6-25.
 */
@Component
public class MessageNotifyHandler extends BaseHandler {
    private HashSet<WebSocketSession> openSessions = new HashSet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        openSessions.add(session);
    }

    public void notifyAllUser(Object message) {
        for (Iterator<WebSocketSession> iterator = openSessions.iterator(); iterator.hasNext(); ) {
            WebSocketSession s = iterator.next();
            try {
                if (s.isOpen()) {
                    s.sendMessage(new TextMessage(JSON.toJSONString(message)));
                } else {
                    iterator.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        openSessions.remove(session);
        LOGGER.info("[WebLogHandler:onClose] a session close,sessionId:[{}]", session.getId());
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        LOGGER.info("[MessageNotifyHandler:onMessage] received a message，close the session,message:[{}],sessionId:[{}]", message, session.getId());
        try {
            session.close();
        } catch (IOException e) {
            LOGGER.error("[MessageNotifyHandler:onMessage] close session error,sessionId:[{}]", session.getId());
        }
    }

    @Override
    public String[] getPaths() {
        return new String[]{"/notify"};
    }

}
